package com.yanq.liancar.fragment;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.PurchaseSuccessActivity;
import com.yanq.liancar.activity.SmallCDelicateCarWashActivity;
import com.yanq.liancar.activity.SmallCDelicateShopActivity;
import com.yanq.liancar.adapter.CouponAdapter;
import com.yanq.liancar.adapter.LuckDrawListAdapter;
import com.yanq.liancar.adapter.ServiceQAdapter;
import com.yanq.liancar.adapter.ServiceVoucherAdapter;
import com.yanq.liancar.base.BaseLYFragment;
import com.yanq.liancar.bean.CouponBean;
import com.yanq.liancar.bean.DaijinQuanBean;
import com.yanq.liancar.bean.QueryUserBaseMessageBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.QRCodeUtil;
import com.yanq.liancar.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class CouponFragment extends BaseLYFragment {

    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.ll_noMessage)
    LinearLayout ll_noMessage;

    private int page = 1;
    private boolean isClear=true;
    private int type,where;         //where: 1：代金券   2：服务券
    private String url,status;
    private CouponAdapter adapter;
    private ServiceQAdapter serviceQAdapter;
    private List<CouponBean.DataBean> mFList = new ArrayList<>();
    private List<DaijinQuanBean.DataBean> mDList = new ArrayList<>();

    public static CouponFragment newInstance(int type,int where) {
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        bundle.putInt("where", where);
        CouponFragment couponFragment = new CouponFragment();
        couponFragment.setArguments(bundle);
        return couponFragment;
    }

    @Override
    protected void onCreateViewLazy(Bundle savedInstanceState) {
        super.onCreateViewLazy(savedInstanceState);
        setContentView(R.layout.frgment_coupon);
        type=getArguments().getInt("type");
        where=getArguments().getInt("where");
        LogUtils.e("type",type+"===="+where);
        if (where==1){
            url="llc/api/selectCashCoupon";
            status="cashcoupon_status";
        }else {
            url="llc/api/selectServiceVoucher";
            status="service_status";
        }
        initOkGoWhole();
        initRecyclerview();
        initListener();
    }

    private void initRecyclerview() {
        recyclerview.setNestedScrollingEnabled(false);
        recyclerview.setLayoutManager(new LinearLayoutManager(mActivity));
        if (where==1){
            serviceQAdapter=new ServiceQAdapter(R.layout.item_coupon,mDList);
            recyclerview.setAdapter(serviceQAdapter);
            serviceQAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    if (mDList.get(position).getCashcoupon_status()==0){
                        RxActivityTool.skipActivity(mActivity, SmallCDelicateShopActivity.class);
                    }
                }
            });
        }else {
            adapter = new CouponAdapter(R.layout.item_coupon, mFList);
            recyclerview.setAdapter(adapter);
            adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    if (mFList.get(position).getService_status()==0){
                        myDialog(mFList.get(position).getType_code());
                    }
                }
            });
        }
    }

    private void initListener() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                isClear = true;


                refreshlayout.finishRefresh();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                isClear = false;

                refreshLayout.finishLoadMore();
            }

        });
    }


    //全部
    private void initOkGoWhole() {
        OkGo.<String>post(Config.s + url)
                .tag(this)
                .params("token", UserBean.getcToken(mActivity))
                .params(status, type)
//                .params("page", page)
//                .params("num", 7)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        if (where==1){
                            DaijinQuanBean bean=gson.fromJson(response.body(), DaijinQuanBean.class);
                            if (bean.isIsSuccess()){
                                if (isClear){
                                    mDList.clear();
                                }
                                mDList.addAll(bean.getData());
                                serviceQAdapter.setNewData(mDList);
                                if (mDList.size()<1){
                                    ll_noMessage.setVisibility(View.VISIBLE);
                                }else {
                                    ll_noMessage.setVisibility(View.GONE);
                                }
                            }else {
                                RxToast.error(bean.getOutputMessage());
                            }
                        }else {
                            CouponBean bean = gson.fromJson(response.body(), CouponBean.class);
                            if (bean.isIsSuccess()) {
                                if (isClear){
                                    mFList.clear();
                                }
                                mFList.addAll(bean.getData());
                                adapter.setNewData(mFList);
                                if (mFList.size()<1){
                                    ll_noMessage.setVisibility(View.VISIBLE);
                                }else {
                                    ll_noMessage.setVisibility(View.GONE);
                                }
                            } else {
                                RxToast.error(bean.getOutputMessage());
                            }
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        RxToast.error("服务器连接超时");
                        super.onError(response);
                    }
                });
    }

        private void myDialog(String code){
            final Dialog bottomDialog = new Dialog(mActivity);
            View contentView = LayoutInflater.from(mActivity).inflate(R.layout.dialog_qrcode, null);
            bottomDialog.setContentView(contentView);
            ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
            params.width = getResources().getDisplayMetrics().widthPixels -100;
            contentView.setLayoutParams(params);
            bottomDialog.getWindow().setGravity(Gravity.CENTER_HORIZONTAL);
            bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation2);
            bottomDialog.setCanceledOnTouchOutside(true);
            bottomDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
            bottomDialog.show();

            ImageView imageView = bottomDialog.findViewById(R.id.img_code);
            Bitmap bitmap= QRCodeUtil.createQRCodeBitmap(code,dp2px(mActivity, 150),dp2px(mActivity, 150));
            imageView.setImageBitmap(bitmap);
        }

    //dp转px
    public static int dp2px(Context context, float dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal,
                context.getResources().getDisplayMetrics());
    }
}
